package com.tenbent.product.base.dto.change;

import com.tenbent.product.base.bo.BizObject;
import com.tenbent.product.base.query.page.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于转换bo与dto互相转换
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/8/29.
 */
@Component(value = "changeBoToDto")
public class ChangeBoToDto {

	private static final Logger logger = LoggerFactory.getLogger(ChangeBoToDto.class);

	/**
	 * 用于 bo list 转换为 dto list
	 *
	 */
	public <T> List<T> changesToDTOList(List<? extends BizObject> bos, Class<T> clazz) {
		if (bos == null || bos.isEmpty()) {
			return new ArrayList<>(0);
		}
		List<T> dtos = new ArrayList<>(bos.size());
		for (BizObject bizObject : bos) {
			try {
				Constructor con = clazz.getConstructor(bizObject.getClass());
				dtos.add((T) con.newInstance(bizObject));
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("changesToDTOList is error : {}", e);
			}
		}
		return dtos;
	}

	/**
	 * 用于 转换 分页 DTO
	 *
	 */
	public <T> PageResult<T> changesToDTOPage(PageResult<? extends BizObject> resultBo, Class<T> clazz) {
		if (resultBo.isEmpty()) {
			return new PageResult<>(0, resultBo.getPageable());
		}
		PageResult<T> resultDto = new PageResult<>(resultBo.getTotal(), resultBo.getPageable());
		resultDto.addAll(changesToDTOList(resultBo, clazz));
		return resultDto;
	}
}
